package com.chapp.ui;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.chapp.R;
import com.chapp.base.Artist;
import com.chapp.base.Event;
import com.chapp.base.Venue;
import com.chapp.lastFmWs.LastFmService;
import com.chapp.lastFmWs.parser.SearchResponse;
import com.chapp.provider.handler.ArtistHandler;
import com.chapp.provider.handler.VenueHandler;
import com.chapp.util.ListAdapter;
import com.chapp.util.Utils;
import com.github.droidfu.widgets.WebImageView;

public class ArtistVenue extends Activity {

	Context context = ArtistVenue.this;

	private ListView lista;
	private AsyncRestClientCaller asyncTask = new AsyncRestClientCaller();

	private Artist artist = null;
	private Venue venue = null;

	Object param = null;
	private CheckBox favorite;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.artist_venue_ui);
		findViewById(R.id.separator03).setVisibility(View.VISIBLE);
		findViewById(R.id.toolbar_btn_search).setVisibility(View.VISIBLE);

		param = getIntent().getExtras().get("item");
		favorite = (CheckBox) findViewById(R.id.btn_favorite);
		favorite.setChecked(false);

		lista = (ListView) findViewById(R.id.list);
		lista.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent goResults = new Intent(ArtistVenue.this, Events.class);
				Event e = (Event) arg0.getItemAtPosition((int) arg3);
				goResults.putExtra("event", e);
				startActivity(goResults);
			}
		});
		fillValues();
	}

	private void fillValues() {
		if (param instanceof Artist) {
			findViewById(R.id.toolbar_btn_geo).setVisibility(View.GONE);
			findViewById(R.id.separator02).setVisibility(View.GONE);
			findViewById(R.id.description_item).setVisibility(View.GONE);
			TextView toolbar = (TextView) findViewById(R.id.toolbar_title);
			toolbar.setText("Artiste");
			artist = (Artist) param;
			Artist artistAux = ArtistHandler.getArtistByName(context,
					artist.getName());
			if (artistAux != null) {
				artist.setId(artistAux.getId());
				favorite.setChecked(true);
			}
			WebImageView photo = (WebImageView) findViewById(R.id.image_item);
			if (artist.getThumbnailURL() == null
					|| artist.getThumbnailURL().equals(""))
				photo.setNoImageDrawable(R.drawable.icon);
			else {
				photo.setImageUrl(artist.getThumbnailURL());
				photo.loadImage();
			}
			String searched = artist.getName();

			TextView title = (TextView) findViewById(R.id.title_item);
			title.setText(searched);

			asyncTask.execute("artist", searched);
		} else if (param instanceof Venue) {
			findViewById(R.id.toolbar_btn_geo).setVisibility(View.VISIBLE);
			findViewById(R.id.separator02).setVisibility(View.VISIBLE);
			findViewById(R.id.description_item).setVisibility(View.VISIBLE);
			TextView toolbar = (TextView) findViewById(R.id.toolbar_title);
			toolbar.setText("Lieu");
			venue = (Venue) param;
			Venue venueAux = VenueHandler.getVenue(this, venue.getId(), 0);
			if (venueAux != null) {
				venue.setId(venueAux.getId());
				favorite.setChecked(true);
			}
			WebImageView photo = (WebImageView) findViewById(R.id.image_item);
			if (venue.getThumbnailURL() == null
					|| venue.getThumbnailURL().equals(""))
				photo.setNoImageDrawable(R.drawable.icon);
			else {
				photo.setImageUrl(venue.getThumbnailURL());
				photo.loadImage();
			}

			TextView title = (TextView) findViewById(R.id.title_item);
			title.setText(venue.getName());
			TextView description = (TextView) findViewById(R.id.description_item);
			description.setText(venue.getLocation().getCountry());
			asyncTask.execute("venue", venue.getId());
		}

	}

	/**
	 * @author Fx!
	 * 
	 */
	private class AsyncRestClientCaller extends
			AsyncTask<String, Void, SearchResponse<Event>> {

		@Override
		protected void onPreExecute() {
			showDialog(0);
		}

		@Override
		protected SearchResponse<Event> doInBackground(String... params) {
			if (params[0].equals("artist")) {
				return LastFmService.searchArtistEvents(context, params[1], 1);
			} else {
				return LastFmService.searchVenueEvents(context, params[1], 1);
			}
		}

		@Override
		protected void onPostExecute(SearchResponse<Event> result) {
			dismissDialog(0);
			if (result != null) {
				if (result.isStatusOk()) {
					if (result.getTotalResults() > 0
							|| result.getSearchList() != null) {
						lista = (ListView) findViewById(R.id.list);

						ListAdapter adapter = new ListAdapter(context,
								result.getSearchList());

						lista.setAdapter(adapter);
					} else {
						Utils.messageToast(context, "0 Results");
						finish();
					}
				} else {
					Utils.messageToast(context, result.toString());
					finish();
				}
			} else {
				Utils.messageToast(context, "Il y a eu une erreur. Ressayez.");
				finish();

			}
		}
	}

	public void onHomeClick(View v) {
		Utils.goHome(this);
	}

	public void onLocaliseClick(View v) {
		Utils.goMap(this, venue.getLocation().getGeoLat(), venue.getLocation()
				.getGeoLong());
	}

	public void onSearchClick(View view) {
		this.startSearch(null, false, Bundle.EMPTY, false);
	}

	public void onFavoriteClick(View v) {
		if (favorite.isChecked() && !(artist == null)) {
			ArtistHandler.insertArtist(this, artist);
		} else if (favorite.isChecked() && artist == null) {
			VenueHandler.insertVenue(this, venue, 0);
		} else if (!favorite.isChecked() && artist != null) {
			ArtistHandler.delete(this, Integer.valueOf(artist.getId()));
		} else
			VenueHandler.deleteVenue(this, Integer.valueOf(venue.getId()));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		ProgressDialog pDialog = new ProgressDialog(this);
		pDialog.setMessage("Chargement");
		pDialog.setCancelable(true);
		pDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				if (asyncTask != null
						&& asyncTask.getStatus() == AsyncTask.Status.RUNNING) {
					asyncTask.cancel(true);
					asyncTask = null;
					finish();
				}
			}
		});
		return pDialog;
	}
}
